package it.webrules.deploymanager.core;

import it.webrules.xsd.dmc.config.v1.GeneralConfig;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.NamingException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MailService {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	private final Session session;

	public MailService(GeneralConfig config) {

		Properties props = new Properties();

		props.put("mail.smtp.from", "noreply@webrules.it");
		props.put("mail.smtp.connectiontimeout", 30000);
		props.put("mail.smtp.timeout", 30000);

		if (config != null) {
			if (config.getSmtpServer() != null)
				props.put("mail.smtp.host", config.getSmtpServer());

			if (config.getSmtpPort() != null)
				props.put("mail.smtp.port", config.getSmtpPort());

			if (config.getSmtpDebug() != null)
				props.put("mail.debug", config.getSmtpDebug());

			if (config.getSmtpFrom() != null)
				props.put("mail.smtp.from", config.getSmtpFrom());
		}

		session = Session.getDefaultInstance(props);
	}

	public void send(String mailAddressTo, String mailSubject, String content) {

		try {

			send(mailAddressTo, null, mailSubject, content);

		} catch (Exception e) {
			logger.error("Error sending mail", e);
		}

	}

	private void send(String mailAddressTo, String mailAddressFrom, String mailSubject, String content) throws MessagingException,
			NamingException {

		logger.debug("Sending mail to '{}', subject '{}'", mailAddressTo, mailSubject);

		Message message = new MimeMessage(session);

		if (mailAddressFrom != null)
			message.setFrom(new InternetAddress(mailAddressFrom));

		String[] stos = mailAddressTo.split(",");
		InternetAddress tos[] = new InternetAddress[stos.length];
		for (int i = 0; i < tos.length; i++)
			tos[i] = new InternetAddress(stos[i]);
		message.setRecipients(Message.RecipientType.TO, tos);

		if (mailSubject != null)
			message.setSubject(mailSubject);

		message.setContent(content, "text/plain");

		Transport.send(message);

	}

}
